<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;

class GoodsContentText extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 商品关联
     */
    public function goods()
    {
        return $this->belongsTo('Goods', 'goods_id');
    }

    /**
     * 处理图文内容授权
     * @param string $content 原始内容
     * @param bool $hasAuth 是否有权限
     * @return string 处理后的内容
     */
    public static function handleAuthContent($content, $hasAuth = false)
    {
        return $hasAuth ? $content : '需要购买后查看图文内容';
    }

    /**
     * 获取指定商品的图文内容
     * @param int $goodsId 商品ID
     * @param bool $withContent 是否包含内容
     * @return \think\Model|null
     */
    public static function getGoodsTextContent($goodsId, $withContent = false)
    {
        $query = self::where('goods_id', $goodsId);

        if (!$withContent) {
            $query->field('id, goods_id, create_time, update_time');
        }

        return $query->find();
    }



    /**
     * 创建或更新商品图文内容
     * @param int $goodsId 商品ID
     * @param array $data 内容数据
     * @return self
     */
    public static function createOrUpdate($goodsId, $data)
    {
        $textContent = self::where('goods_id', $goodsId)->find();

        if (!$textContent) {
            $textContent           = new self();
            $textContent->goods_id = $goodsId;
        }

        $textContent->content = $data['content'] ?? '';
        $textContent->save();

        return $textContent;
    }
}
